package org.wlgzs.moyue.service.servicelmpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import org.wlgzs.moyue.dao.SensitiveWordDao;
import org.wlgzs.moyue.entity.SensitiveWord;
import org.wlgzs.moyue.service.SensitiveWordService;
import org.wlgzs.moyue.util.Result;
import org.wlgzs.moyue.util.ResultCode;

import javax.naming.NamingEnumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Auther: dayfly
 * @Date: 2018/4/24 20:03
 * @Description:
 */

@Service
public class SensitiveWordImpl implements SensitiveWordService {
    @Autowired
    private SensitiveWordDao sensitiveWordDao;

    public Result addSensitiveWord(String word) {
        SensitiveWord sensitiveWord = new SensitiveWord();
        sensitiveWord.setSensitiveWord(word);
        sensitiveWordDao.save(sensitiveWord);
        return new Result(ResultCode.SUCCESS);

    }

    public Result deleteSensitiveWord(long wordId) {
        sensitiveWordDao.deleteByWordId(wordId);
        return new Result(ResultCode.SUCCESS);
    }

    public ModelAndView showAllSensitiveWords(String pageNum, Model model) {
        int page;
        if (pageNum == null) page = 1;
        else page = Integer.parseInt(pageNum);
        Pageable pageable = new PageRequest(page - 1, 20);
        Page<SensitiveWord> wordPage = sensitiveWordDao.findAll(pageable);
        model.addAttribute("page", wordPage.getNumber() + 1);
        model.addAttribute("pages", wordPage.getTotalPages());
        model.addAttribute("words", wordPage.getContent());
        System.out.println("内容为：" + wordPage.getContent());
        return new ModelAndView("sensitive");

    }

    public Result updateSensitiveWord(SensitiveWord sensitiveWord) {
        sensitiveWordDao.save(sensitiveWord);
        return new Result(ResultCode.SUCCESS);
    }


    public Result mateWord(String word) {
        List<SensitiveWord> sensitiveWords = sensitiveWordDao.findAll();
        for (int i = 0; i < sensitiveWords.size(); i++) {
            String pattern = sensitiveWords.get(i).getSensitiveWord();
            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(word);
            if (m.find()) return new Result(ResultCode.FAIL);
        }
        return new Result(ResultCode.SUCCESS);
    }

}

